#!/usr/bin/env node
import fs from 'fs'
import path from 'path'
import chalk from 'chalk'
import { fileURLToPath } from 'url'
import readline from 'readline'

const __dirname = path.dirname(fileURLToPath(import.meta.url))
const DOCS_DIR = path.join(__dirname, '../docs/vue-component-docs')

// 文档索引
const DOC_INDEX = {
  'component-creation': 'component-creation-guide.md',
  'component-comm': 'component-communication.md',
  'design-patterns': 'component-design-patterns.md',
  'component-lib': 'component-library-guide.md',
  'theme': 'theme-customization-guide.md',
  'i18n': 'i18n-a11y-guide.md',
  'testing': 'component-testing-guide.md',
  'docs': 'component-documentation-guide.md',
  'learn': 'learning-path.md',
  'tree': 'DOCUMENTATION-TREE.md'
}

// 创建命令行接口
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout
})

function showHelp() {
  console.log(chalk.blue('\nVue 文档助手使用指南\n'))
  console.log('可用命令:')
  console.log('  list       - 列出所有文档')
  console.log('  search <词> - 搜索文档内容')
  console.log('  open <文档> - 打开指定文档')
  console.log('  help       - 显示帮助信息')
  console.log('  exit       - 退出程序\n')
  console.log('文档缩写:')
  Object.entries(DOC_INDEX).forEach(([key, file]) => {
    console.log(`  ${key.padEnd(15)} - ${file}`)
  })
}

function listDocs() {
  console.log(chalk.green('\n可用文档:\n'))
  fs.readdirSync(DOCS_DIR).forEach(file => {
    if (file.endsWith('.md')) {
      console.log(`- ${file}`)
    }
  })
}

function searchDocs(term) {
  console.log(chalk.yellow(`\n搜索: "${term}"\n`))
  let found = false
  
  fs.readdirSync(DOCS_DIR).forEach(file => {
    if (file.endsWith('.md')) {
      const content = fs.readFileSync(path.join(DOCS_DIR, file), 'utf8')
      if (content.includes(term)) {
        console.log(chalk.green(`匹配到: ${file}`))
        found = true
        
        // 显示匹配上下文
        const lines = content.split('\n')
        lines.forEach((line, i) => {
          if (line.includes(term)) {
            console.log(`  ${i+1}: ${line.trim()}`)
          }
        })
        console.log()
      }
    }
  })
  
  if (!found) {
    console.log(chalk.red('未找到匹配的文档内容'))
  }
}

function openDoc(docKey) {
  const docFile = DOC_INDEX[docKey] || docKey
  const docPath = path.join(DOCS_DIR, docFile)
  
  if (fs.existsSync(docPath)) {
    console.log(chalk.green(`\n打开文档: ${docFile}\n`))
    
    // 显示文档开头部分
    const content = fs.readFileSync(docPath, 'utf8')
    console.log(content.split('\n').slice(0, 20).join('\n'))
    console.log(chalk.blue('\n...完整内容请查看文件:', docFile))
  } else {
    console.log(chalk.red(`\n文档不存在: ${docFile}`))
    console.log('使用 "list" 命令查看可用文档')
  }
}

// 主交互循环
function startCLI() {
  console.log(chalk.blue.bold('\nVue 组件开发文档助手 v1.0\n'))
  showHelp()
  
  rl.on('line', (input) => {
    const [cmd, ...args] = input.trim().split(' ')
    
    switch (cmd) {
      case 'list':
        listDocs()
        break
      case 'search':
        if (args.length) searchDocs(args.join(' '))
        else console.log(chalk.red('请提供搜索词'))
        break
      case 'open':
        if (args.length) openDoc(args[0])
        else console.log(chalk.red('请指定文档'))
        break
      case 'help':
        showHelp()
        break
      case 'exit':
        rl.close()
        return
      default:
        console.log(chalk.red(`未知命令: ${cmd}`))
        showHelp()
    }
    
    console.log('\n输入命令 (help 查看帮助):')
  })
  
  rl.on('close', () => {
    console.log(chalk.yellow('\n感谢使用 Vue 文档助手!\n'))
    process.exit(0)
  })
  
  console.log('\n输入命令 (help 查看帮助):')
}

// 启动程序
startCLI()